import React, { Component, PropTypes } from 'react';
import { Utility, GxIcon, RelationItem, ApiInfo, Refresh } from 'components';
import { connect } from 'react-redux';
import * as CommonActions from 'redux/modules/reduxCommon';
const styles = require('./scss/RelationTask.scss');

@connect(
  state => ({
    Title: state.Common.Title,                                          // 标题
    UrlParams: state.Common.UrlParams,                                  // URL参数
    RelationTaskList: state.Common.RelationTaskList,                    // 相关任务列表
  }),
  { ...CommonActions })

export default class RelationTask extends Component {
  static propTypes = {
    Title: PropTypes.string,                                            // 标题
    UrlParams: PropTypes.object,                                        // url 参数
    RelationTaskList: PropTypes.object,                                 // 相关任务列表
    onDeleteByFields: PropTypes.func,                                   // 删除
    onSetContent: PropTypes.func,                                       // 保存
    onUpdateRedux: PropTypes.func,                                      // 更新
    onApiGet: PropTypes.func,                                           // get request
    onApiPut: PropTypes.func,                                           // put request
    onUpdateListRelationState: PropTypes.func,                          // update relation
  };

  constructor(props) {
    super(props);
    this.state = { RefreshComplete: true, NextDataComplete: true, };
    const _RelationTaskList = [
      {
        content: '天有牛郞织女，地上金童玉女，唯吾与尔。', scope: 'MYSELF', pId: 7218,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '七夕如愿盼今朝，红叶香残怨可消。朝朝暮暮图永久，缠缠绵绵诉心焦。', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }]
      },
      {
        content: '亲亲你我， 私守楼阁，鹊桥之夜永定今生!', scope: 'ALL', pId: 361827,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '银河之上，一世的等待', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '银河陷落，爱意沸腾，总不比乞巧合欢。', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '银河陷落，爱意沸腾，总不比乞巧合欢。', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '银河陷落，爱意沸腾，总不比乞巧合欢。', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '银河陷落，爱意沸腾，总不比乞巧合欢。', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '银河陷落，爱意沸腾，总不比乞巧合欢。', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '银河陷落，爱意沸腾，总不比乞巧合欢。', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '银河陷落，爱意沸腾，总不比乞巧合欢。', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '银河陷落，爱意沸腾，总不比乞巧合欢。', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '银河陷落，爱意沸腾，总不比乞巧合欢。', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
    ];
    this.state.RelationTaskList = _RelationTaskList;
  }

  componentDidMount() {
    this.state.IsMount = true;
    const { UrlParams } = this.props;
    const { uuid, role } = UrlParams || {};
    console.log(uuid);
    this.state.super_uuid = uuid;
    this.state.role = role;
    // const { List } = RelationTaskList || {};
    // if (!Utility.isArray(List)) {
    // }
    this.__InitData({ uuid: uuid });
    this.__UpdateRender();
  }

  componentWillUnmount() {
    delete this.state.IsMount;
  }

  /**
   * 更新渲染
   */
  __UpdateRender() {
    if (!!this.state.IsMount) {
      this.setState({ __CurrentTempDate: new Date().getTime() });
    }
  }

  __InitData(condition) {
    const params = Object.assign({}, { pg_index: 0, pg_count: 16 }, condition || {});
    const { onApiGet } = this.props;
    if (!Utility.isFunction(onApiGet)) {
      return;
    }

    const __Complete = () => {
      delete this.state.IsBusying;
      this.state.NextDataComplete = true;
      this.state.RefreshComplete = true;
      this.__UpdateRender();
    };
    const __self = this;
    onApiGet('RelationTaskList', ApiInfo.Task.Relationtask, { params: params }).then(() => {
      __self.__InitDataByResult();
      __Complete();
    }, () => {
      __Complete();
    });
  }

  __InitDataByResult() {
    const { RelationTaskList } = this.props;
    const { Condition } = RelationTaskList || {};
    const { IsExistsNextData } = Condition || {};
    this.state.IsNextData = IsExistsNextData;
  }

  __HandlerNextData() {
    const { RelationTaskList } = this.props;
    const { Condition } = RelationTaskList || {};
    const { IsExistsNextData } = Condition || {};
    this.state.IsNextData = IsExistsNextData;
    if (!IsExistsNextData) {
      return;
    }
    this.state.NextDataComplete = false;
    this.__UpdateRender();
    this.__InitData(Condition, true);
  }

  __HandlerRefresh() {
    this.state.RefreshComplete = false;
    this.__UpdateRender();
    const { UrlParams } = this.props;
    const { uuid } = UrlParams || {};
    this.__InitData({ uuid: uuid }, false);
  }

  __HandlerRelation(item) {
    this.__StopPropagation(item);
    if (!item) {
      return;
    }
    const { onApiPut, onUpdateListRelationState, onUpdateRedux } = this.props;
    if (!Utility.isFunction(onApiPut)) {
      return;
    }
    const { uuid, isRelation } = item || {};
    const __params = {};
    __params.super_uuid = this.state.super_uuid;
    __params.child_uuid = uuid;
    __params.type = isRelation === 0 ? 1 : 0;
    const _isRelation = isRelation === 0 ? 1 : 0;
    const self = this;
    const __Submit = () => {
      Utility.$loading();
      onApiPut('RelationTaskInfo', ApiInfo.Task.Relation, { params: __params }).then(() => {
        // onUpdateListRelationState('TaskRelatedInfo', { uuid: uuid, isRelation: _isRelation });
        onUpdateListRelationState('RelationTaskList', { uuid: uuid, isRelation: _isRelation });
        onUpdateRedux();
        self.__UpdateRender();
        Utility.$actionSheet(isRelation === 0 ? '关联成功' : '取消成功');
        Utility.$loadingHide();
      }, () => {
        Utility.$loadingHide();
      });
    };
    Utility.$showDialogConfirm(isRelation === 0 ? '确认关联任务?' : '确认取消关联?', null, () => {
      __Submit();
    });
  }

  __BuildHTML() {
    const { RelationTaskList } = this.props;
    const { List } = RelationTaskList || {};
    if (!Utility.isArray(List)) {
      return null;
    }
    const { Task } = Utility.constItem.UrlItem;
    return List.map((item, index) => {
      const { content, extTaskUser, scope, isRelation, uuid } = item || {};
      const _relationInfo = {};
      _relationInfo.content = content || '';
      _relationInfo.extTaskUser = extTaskUser || [];
      _relationInfo.scope = scope || '';
      _relationInfo.isRelation = isRelation;
      return (
        <div className={styles.relationContainer + ' ' + (index === List.length - 1 ? styles.lastCss : '')}
          onClick={() => {
            Utility.toPage(Task, { taskId: uuid });
          }}
          key={'relation_list_' + index}>
          <RelationItem RelationInfo={_relationInfo} onSelect={this.__HandlerRelation.bind(this, item)} />
        </div>
      );
    });
  }

  /**
   * 取消冒泡
   */
  __StopPropagation(ee) {
    if (ee && ee.stopPropagation) {
      ee.stopPropagation();
      ee.preventDefault();
    } else {
      window.event.cancelBubble = true;
    }
  }

  /**
   * 页面跳转。
   * @param params
   * @private GmessageView
   */
  __HandlerGoToPage(url, params) {
    Utility.toPage(url, params);
  }

  render() {
    const { RefreshComplete, NextDataComplete, IsNextData } = this.state;
    const { TaskRelated } = Utility.constItem.UrlItem;
    // this.state.role === Utility.constItem.User.User_Author
    return (
      <div className={styles.relationTaskCss}>
        <div className={styles.relatedCss}>
          <div className={styles.outCss} onClick={this.__HandlerGoToPage.bind(this, TaskRelated, { super_uuid: this.state.super_uuid })}>
            <GxIcon IconType="iconRelation" />关联任务
          </div>
        </div>
        <Refresh Percentage={20} RefreshComplete={RefreshComplete} NextDataComplete={NextDataComplete}
          onRefresh={this.__HandlerRefresh.bind(this)} onNextData={this.__HandlerNextData.bind(this)}>
          <div className={styles.list}>
            {
              this.__BuildHTML()
            }
          </div>
        </Refresh>
        <div className={styles.last}>
          {
            IsNextData === false &&
            <span> 没有相关任务了!</span>
          }
        </div>
      </div>
    );
  }
}
